




/**
 * Created by kevin on 2018/2/6.
 */
var express = require('express');
var router = express.Router();

router.get('/ios.sh', function(req, res) {

    let configBase64 = req.query.c;

    let cf = new Buffer(configBase64,'base64').toString();

    let configObj = JSON.parse(cf);
    console.log(configObj);
    let projectName = configObj.n;
    let gitUrl = configObj.u;
    let branch = configObj.b;
    let sign = configObj.s;
    let version =configObj.v;
    let build = configObj.bd;
    let bundleId = configObj.bi;
    let id = configObj.id;
    let backUrl = configObj.cb;
    let config = configObj.cf;
    let teamid = configObj.ti;
    let gitPath = configObj.gp;
    var prefix = configObj.prefix;
    var suffix = configObj.suffix;

    prefix = prefix.replace(/&nbsp;/g," ");
    prefix = prefix.replace(/&nbcl;/g,"\n");
    suffix = suffix.replace(/&nbsp;/g," ");
    suffix = suffix.replace(/&nbcl;/g,"\n");

    let bash = `
    #!/bin/bash
    export LANG=en_US.UTF-8
    export LANGUAGE=en_US.UTF-8
    export LC_ALL=en_US.UTF-8
    
    ${prefix}
    
    project_name=${projectName}
    git_url=${gitUrl}
    branch=${branch}
    profile=${sign}
    version_string=${version}
    build_number=${build}
    bundleId=${bundleId}
    package_id=${id}
    url=${backUrl}
    configuration=${config}
    gitPath=${gitPath}
    teamId=${teamid}

    CURRENT_USER=\`whoami\`
    USER_DIR=/Users/\${CURRENT_USER}
    \${USER_DIR}/iPack/iOS/Scripts/keychain.sh
    git_base_path=\${USER_DIR}/iPack/iOS/Archive/\${project_name}/\${branch}
    if [ ! -d \${git_base_path} ];
    then
        mkdir -p \${git_base_path}
    fi
    cd $git_base_path

    # 拼接路径
    if [ \${#gitPath} != 0 ];
    then
        to_project_path=\${git_base_path}/\${gitPath}
    else
        to_project_path=\${git_base_path}
    fi

    if [ ! -d \${to_project_path}/\${project_name} ];
    then
        git clone -b $branch $git_url
        if [ $? != 0  ]
        then
            echo '拉取代码失败'
            exit 1
        fi
        cd \${to_project_path}/\${project_name}
    else
        cd \${to_project_path}/\${project_name}
        git checkout .
        git pull
        if [ $? != 0  ];
        then
            echo '更新代码失败'
            exit 1
        fi
    fi
    /usr/local/bin/pod repo update hui10-hui10-ios-hui10repos
    /usr/local/bin/pod update --no-repo-update
    if [ $? != 0  ];
    then
        echo '拉取模块时出现错误'
        exit 1
    fi

    # 工程环境路径
    workspace_path=\${to_project_path}/\${project_name}

    # 打包项目名字
    scheme_name=\${project_name}

    # 指定app的输出位置

    if [ ! -d \${USER_DIR}/iPack/iOS/Packages/\${project_name}/\${branch}_\${version_string}/build ];
    then
        mkdir -p \${USER_DIR}/iPack/iOS/Packages/\${project_name}/\${branch}_\${version_string}/build
    fi
    build_path=\${USER_DIR}/iPack/iOS/Packages/\${project_name}/\${branch}_\${version_string}/build

    # 指定.ipa的输出位置
    ipa_path=\${USER_DIR}/iPack/iOS/Packages/\${project_name}/\${branch}_\${version_string}

    # info.plist文件的位置
    info_plist=\${workspace_path}/\${project_name}/Info.plist

    # 下面是读取.plist文件的位置然后修改版本号和build号，这点没有使用xcodebuild提供的命令，在上面也有叙述
    # 修改版本号
    /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $version_string" \${info_plist}

    # 修改build号
    /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $build_number" \${info_plist}

    # 生成app, 在build_path路径下面
    # xcodebuild -workspace \${workspace_path}.xcworkspace -scheme \${scheme_name} -configuration Release clean -sdk iphoneos build CODE_SIGN_IDENTITY="\${CODE_SIGN_IDENTITY}" PROVISIONING_PROFILE="\${PROVISIONING_PROFILE}" SYMROOT="\${build_path}"

    # clean
    xcodebuild clean -workspace \${project_name}.xcworkspace -scheme \${scheme_name} -configuration \${configuration}
    if [ $? != 0  ];
    then
        echo '清理过程中出现问题'
        exit 1
    fi
    # 导出 xcarchive
    xcodebuild archive -workspace \${project_name}.xcworkspace -scheme \${scheme_name} -configuration \${configuration} -archivePath \${build_path}/\${project_name}.xcarchive
    if [ $? != 0  ];
    then
        echo '生成xcarchive过程中出现问题'
        exit 1
    fi

    # 生成导出选项
    cat << EOF > \${USER_DIR}/iPack/iOS/Plist/options.plist
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
        <dict>
        <key>provisioningProfiles</key>
        <dict>
        <key>\${bundleId}</key>
        <string>\${profile}</string>
        </dict>
        <key>signingStyle</key>
        <string>manual</string>
        <key>teamID</key>
        <string>\${teamId}</string>
        <key>compileBitcode</key>
        <false/>
        <key>method</key>
        <string>ad-hoc</string>
        </dict>
        </plist>
        EOF

    # 导出ipa包
    xcodebuild -exportArchive -archivePath \${build_path}/\${project_name}.xcarchive -exportPath \${ipa_path}/\${build_number} -exportOptionsPlist ~/iPack/iOS/Plist/options.plist
    if [ $? != 0  ];
        then
        echo '导出ipa文件出现问题'
        exit 1
    fi
    
    # 生成ipa, 在ipa_path路径下面
    # xcrun -sdk iphoneos -v PackageApplication \${build_path}/Release-iphoneos/\${project_name}.app -o \${ipa_path}/\${build_number}.ipa
    mv \${ipa_path}/\${build_number}/\${project_name}.ipa \${ipa_path}/\${bundleId}-\${version_string}-\${build_number}.ipa
    rmdir \${ipa_path}/\${build_number}

    ipaFile=\${ipa_path}/\${bundleId}-\${version_string}-\${build_number}.ipa

    result=\`curl -F "package=@\${ipaFile}" -F "package_id=\${package_id}" \${url}/package/upload\`;
    rightContent=\`echo $result | grep '^{' | grep '}$'\`
    if [ \${#rightContent} == 0 ]; 
    then
        echo '上传文件出现问题';
        exit 1
    else
        code=$(echo -e \${result\/\/,\/\\\\n} | grep 'code' | cut -d : -f 2)
        echo -e $code
        if [ $code == 0 ];
        then
            ${suffix}
            exit 0
        else
            echo -e \${result\/\/,\/\\\\n} | grep 'message' | cut -d : -f 2
            exit 1
        fi
    fi`;

    res.send(bash);
});

router.get('/android.sh', function(req, res) {

    let configBase64 = req.query.c;

    let cf = new Buffer(configBase64,'base64').toString();

    let configObj = JSON.parse(cf);

    let projectName = configObj.n;
    let gitUrl = configObj.u;
    let branch = configObj.b;
    let config = configObj.cf;
    let version =configObj.v;
    let build = configObj.bd;
    let bundleId = configObj.bi;
    let id = configObj.id;
    let backUrl = configObj.cb;
    let gitPath = configObj.gp;
    var prefix = configObj.prefix;
    var suffix = configObj.suffix;

    prefix = prefix.replace(/&nbsp;/g," ");
    prefix = prefix.replace(/&nbcl;/g,"\n");
    suffix = suffix.replace(/&nbsp;/g," ");
    suffix = suffix.replace(/&nbcl;/g,"\n");

    let bash = `
    #!/bin/sh

    GIT_ADDRESS=${gitUrl}
    PROJECT_NAME=${projectName}
    BRANCH=${branch}
    CONFIGURATION=${config}
    VERSION=${version}
    BUILD_NUM=${build}
    BUNDLE_ID=${bundleId}
    PACKAGE_ID=${id}
    UPLOAD_URL=${backUrl}
    GIT_PATH=${gitPath}

    export LANG=en_US.UTF-8
    export LANGUAGE=en_US.UTF-8
    export LC_ALL=en_US.UTF-8

    CURRENT_USER=\`whoami\`
    if [ \`uname\` == 'Linux' ]; 
    then
        USER_DIR=/home
    elif [ \`uname\` == 'Darwin' ]; 
    then
        USER_DIR=/Users
    fi

    ${prefix}
    
    GIT_BASE_PATH=\${USER_DIR}/\${CURRENT_USER}/iPack/Android/Archive/\${PROJECT_NAME}/\${BRANCH}
    if [ ! -d \${GIT_BASE_PATH} ];
    then
        mkdir -p \${GIT_BASE_PATH}
    fi

    cd \${GIT_BASE_PATH}

    if [ \${#GIT_PATH} != 0 ];
    then
        to_project_path=\${GIT_BASE_PATH}/\${GIT_PATH}
    else
        to_project_path=\${GIT_BASE_PATH}
    fi

    ASSEMBLE_INFO=\`echo $CONFIGURATION | awk '{for(i=1;i<=NF;i++) {printf "%s%s ", toupper(substr($i,1,1)),substr($i,2)};printf ORS}'\`

    if [ ! -d \${to_project_path}/\${PROJECT_NAME} ]; 
    then
        git clone -b \${BRANCH} \${GIT_ADDRESS}
        if [ $? != 0  ];
        then
            echo '拉取代码失败'
            exit 1
        fi
        cd \${to_project_path}/\${PROJECT_NAME}
        chmod +x ./gradlew
        ./gradlew clean assemble\${ASSEMBLE_INFO} -Pversion_name=\${VERSION} -Pversion_code=\${BUILD_NUM}
        if [ $? != 0  ];
        then
            echo '打包(gradlew)失败'
            exit 1
        fi
    else
        cd \${to_project_path}/\${PROJECT_NAME}
        git checkout .
        git pull
        if [ $? != 0  ];
        then
            echo '拉取代码失败'
            exit 1
        fi
        chmod +x ./gradlew
        echo \${VERSION}
        echo \${BUILD_NUM}
        ./gradlew assemble\${ASSEMBLE_INFO} -Pversion_name=\${VERSION} -Pversion_code=\${BUILD_NUM}
        if [ $? != 0  ];
        then
            echo '打包(gradlew)失败'
            exit 1
        fi
    fi

    #关掉gradle daemon并释放内存
    #./gradlew --stop
    sync

    function getdir(){
        for element in \`ls $1\`
            do
                dir_or_file=$1"/"$element
        if [ -d $dir_or_file ];
        then
            getdir $dir_or_file
        else
            apk_file=\`echo $dir_or_file|rev|cut -c-4|rev\`
            if [ $apk_file == '.apk' ]; 
            then
                echo \${dir_or_file}
            fi
        fi
        done
    }
    
    files=\`getdir ./app/build/outputs/apk\`
    last_file=\`echo $files | cut -d' ' -f1\`
    if [ ! -d \${USER_DIR}/\${CURRENT_USER}/iPack/Android/Packages ]; 
    then
        mkdir -p \${USER_DIR}/\${CURRENT_USER}/iPack/Android/Packages
    fi
    echo \${last_file}
    mv \${last_file} \${USER_DIR}/\${CURRENT_USER}/iPack/Android/Packages/\${BUNDLE_ID}-\${VERSION}-\${BUILD_NUM}.apk
    rm -rf \${to_project_path}/\${PROJECT_NAME}/app/build/outputs/apk

    apkFile=\${USER_DIR}/\${CURRENT_USER}/iPack/Android/Packages/\${BUNDLE_ID}-\${VERSION}-\${BUILD_NUM}.apk

    result=\`curl -F "package=@\${apkFile}" -F "package_id=\${PACKAGE_ID}" \${UPLOAD_URL}/package/upload\`;
    echo $result
    rightContent=\`echo $result | grep '^{' | grep '}$'\`
    if [ \${#rightContent} == 0 ];
    then
        echo '上传文件出现问题';
        exit 1
    else
        code=$(echo -e \${result\/\/,\/\\\\n} | grep 'code' | cut -d : -f 2)
        echo -e $code
        if [ $code == 0 ];
        then
            ${suffix}
            exit 0
        else
            echo -e \${result\/\/,\/\\\\n} | grep 'message' | cut -d : -f 2
            exit 1
        fi
    fi`;

    res.send(bash);

});

module.exports = router;















